package com.activity;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleAdapter.ViewBinder;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.type.Comment;
import com.type.Commenter;
import com.type.Follower;
import com.type.Photo;

public class FriendTopicFollowDetailActivity extends Activity {
	// constant
	static final int COMPLETE_FETCH_FOLLOW_AND_COMMENT_DETAIL = 1;
	static final int COMPLETE_JOIN_ACTIVITY = 2;
	static final int COMPLETE_ADD_COMMENT = 3;
	static final int SEND_JOIN_ACTIVITY = 5;
	static final int SEND_ADD_COMMENT = 6;
	static final int FETCH_FOLLOW_AND_COMMENT_DETAIL = 7;

	// field
	ListView listView;
	ToggleButton toggleBtnJoinOrQuit;
	Button btnAddComment;
	Button btnPhotoComment;
	
	long myPhoneNum;
	long friendPhoneNum;
	int activityIndex;
	String textComment;
	Bitmap photoComment;
	
	ArrayList<Follower> followerList;
	ArrayList<Commenter> commenterList;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.temp_friend_created_activity_follow_detail_page);

		myPhoneNum = getIntent().getLongExtra(MainActivity.MY_PHONE_NUMBER, 0);
		friendPhoneNum = getIntent().getLongExtra(MainActivity.FRIEND_PHONE_NUMBER, 0);
		activityIndex = getIntent().getIntExtra(FriendTopicActivity.ACTIVITY_INDEX, 0);
		
		toggleBtnJoinOrQuit = (ToggleButton)findViewById(R.id.toggle_btn_join_or_quit_this_activity);
		toggleBtnJoinOrQuit.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(toggleBtnJoinOrQuit.isChecked()) 
					joinActivity();
				else 
					quitActivity();
			}
		});
		btnAddComment = (Button)findViewById(R.id.btn_add_comment);
		btnAddComment.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				showAddCommentDialog();
			}
		});
		
		fetchFollowAndCommentDetail();
	}
	
	
	void showAddCommentDialog() {
		final View dialogView = LayoutInflater.from(this).inflate(R.layout.add_comment_dialog, null);
		btnPhotoComment = (Button) dialogView.findViewById(R.id.ibPhotoComment);
		btnPhotoComment.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
				intent.setType("image/*");
				intent.putExtra("return-data", true);
				startActivityForResult(intent, 0);
			}
		});
		
		(new AlertDialog.Builder(this).setView(dialogView)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int whichButton) {
						textComment = ((EditText) dialogView.findViewById(R.id.etTextComment)).getText().toString();
						if (textComment == null || textComment.length() == 0)
							Toast.makeText(FriendTopicFollowDetailActivity.this, "empty text, please write some text comment", Toast.LENGTH_LONG).show();
						else {
							addComment();
							dialog.dismiss();
						}
					}
				}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				})).create().show();
	}
	
	
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		if (requestCode == 0 && intent != null) {
			photoComment = intent.getParcelableExtra("data");
			Matrix matrix = new Matrix();
			matrix.postScale(130 / (float) photoComment.getWidth(), 100 / (float) photoComment.getHeight());
			btnPhotoComment.setBackgroundDrawable(new BitmapDrawable(Bitmap.createBitmap(photoComment, 0, 0, photoComment.getWidth(), photoComment.getHeight(), matrix, true)));
			btnPhotoComment.setHint("");
		}
	}
	

	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message message) {
			switch(message.what) {
			case COMPLETE_FETCH_FOLLOW_AND_COMMENT_DETAIL:
				showListView();
				break;
			case COMPLETE_JOIN_ACTIVITY:
				
				break;
			case COMPLETE_ADD_COMMENT:
				
				break;
			default:
					break;
			}
			
			if(message.what == COMPLETE_JOIN_ACTIVITY)
				btnAddComment.setVisibility(View.VISIBLE);
			else if(message.what == COMPLETE_ADD_COMMENT) {
				//TODO zyc refresh UI
				
			}
		}
	};
	
	
	void showListView() {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		for(Commenter commenter : commenterList) {
			Map<String, Object> map = new HashMap<String, Object>();
			
			map.put("follower_avatar", null);
			map.put("follower_phone_number", commenter.getPhoneNumber());
			map.put("follower_name", null);
			
			ArrayList<Comment> commentList = commenter.getCommentList();
			String textCommentAll = "";
			for(Comment comment : commentList)
				textCommentAll += comment.getTextComment();
			map.put("commenter_text_comment", textCommentAll);

			Comment lastComment = commentList.get(commentList.size()-1);
			map.put("commenter_photo_comment_last", lastComment.getPhotoComment().fetchBitmap());
			
			list.add(map);
		}
		for(Follower follower : followerList) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("follower_avatar", null);
			map.put("follower_phone_number", follower.getPhoneNumber());
			map.put("follower_name", null);
			map.put("commenter_text_comment", null);
			map.put("commenter_photo_comment_last", null);
			list.add(map);
		}
		
		SimpleAdapter adapter = new SimpleAdapter(FriendTopicFollowDetailActivity.this, 
				list,
				R.layout.temp_friend_created_activity_follow_detail_list_item, 
				new String[]{"activity_photo", "activity_title", "activity_content"}, 
				new int[]{R.id.ivActivityPhoto, R.id.tvActivityTitle, R.id.tvActivityContent});
		adapter.setViewBinder(new ViewBinder() {
			@Override
			public boolean setViewValue(View view, Object data, String textRepresentation) {
				if(data == null)
					return false;
				else if ((view instanceof ImageView) & (data instanceof Bitmap)) {
					ImageView iv = (ImageView) view;
					Bitmap bm = (Bitmap) data;
					iv.setImageBitmap(bm);
					return true;
				} else
					return false;
			}
		});
		
		listView.setAdapter(adapter);
	}
	
	
	void fetchFollowAndCommentDetail() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				Socket socket = null;
				DataOutputStream dos = null;
				DataInputStream dis = null;
				try {
					socket = new Socket(MainActivity.SERVER_IP, 9999);
					dos = new DataOutputStream(socket.getOutputStream());
					dis = new DataInputStream(socket.getInputStream());
					dos.writeInt(FETCH_FOLLOW_AND_COMMENT_DETAIL);
					dos.writeLong(friendPhoneNum);
					dos.writeInt(activityIndex);
					
					int followerCount = dis.readInt();
					if (followerCount > 0) {
						followerList = new ArrayList<Follower>();
						commenterList = new ArrayList<Commenter>();
						for(int i=0; i<followerCount; i++) {
							if(dis.readBoolean()) {
								Commenter commenter = new Commenter();
								commenter.receive(dis);
								commenterList.add(commenter);
							} else {
								Follower follower = new Follower();
								follower.receive(dis);
								followerList.add(follower);
							}
						}
						mHandler.sendEmptyMessageDelayed(COMPLETE_FETCH_FOLLOW_AND_COMMENT_DETAIL, 0);
					}
				} catch (IOException e) {
					e.printStackTrace();
				} catch (InterruptedException e) {
					e.printStackTrace();
				} finally {
					try {
						dis.close();
						dos.close();
						socket.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
	}

	
	void joinActivity() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				Socket socket = null;
				DataOutputStream dos = null;
				DataInputStream dis = null;
				try {
					socket = new Socket(MainActivity.SERVER_IP, 9999);
					dos = new DataOutputStream(socket.getOutputStream());
					dis = new DataInputStream(socket.getInputStream());
					dos.writeInt(SEND_JOIN_ACTIVITY);
					dos.writeLong(friendPhoneNum);
					dos.writeInt(activityIndex);
					dos.writeLong(myPhoneNum);
					mHandler.sendEmptyMessageDelayed(COMPLETE_JOIN_ACTIVITY, 0);
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					try {
						dis.close();
						dos.close();
						socket.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
	}


	void quitActivity() {
		// TODO zyc future
		
		btnAddComment.setVisibility(View.INVISIBLE);
	}

	void addComment() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				Socket socket = null;
				DataOutputStream dos = null;
				DataInputStream dis = null;
				try {
					socket = new Socket(MainActivity.SERVER_IP, 9999);
					dos = new DataOutputStream(socket.getOutputStream());
					dis = new DataInputStream(socket.getInputStream());
					dos.writeInt(SEND_ADD_COMMENT);
					dos.writeLong(friendPhoneNum);
					dos.writeInt(activityIndex);
					dos.writeLong(myPhoneNum);
					dos.writeUTF(textComment);
					(new Photo(photoComment)).send(dos);
					mHandler.sendEmptyMessageDelayed(COMPLETE_ADD_COMMENT, 0);
				} catch (IOException e) {
					e.printStackTrace();
				} catch (InterruptedException e) {
					e.printStackTrace();
				} finally {
					try {
						dis.close();
						dos.close();
						socket.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
	}
}
